<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\index\service;


use app\index\model\LotteryConfig;
use app\index\model\LotteryLog;
use app\index\model\LotteryLogistics;
use app\index\model\LotteryPrize;
use app\index\model\Store;
use app\index\model\User;
use app\index\model\UserLottery;
use app\index\util\Lottery;
use app\utils\Addons;
use think\Exception;

class LotteryService
{
    protected $user;
    protected $mid;
    public function __construct()
    {
        global $user,$mid;
        $this->mid = $mid;
        $this->user = User::find($user['id']);
    }

    public function lotteryGetNumber(int $style) : bool{
        $config = LotteryConfig::field('id,type,limit')
            ->where('style',$style)
            ->where('status',1)
            ->find();
        $where = [['lottery_id','=',$config->id],['user_id' ,'=', $this->user->id]];
        if($config->type == 2)$where[] = ['create_time','>',date('Y-m-d')];
        $number = \think\facade\Db::name('user_lottery_record')
            ->where($where)
            ->sum('number');
        if ($config->limit > $number)
            return true;
        return false;
    }



    public function read(int $id){
        $style = [17 => 1,18 => 2];
        foreach ($style AS $key => $value){
            $is_bool = Addons::check($this->mid,$key);
            if ($is_bool)$in[] = $value;
        }
        if (empty($in))return [HTTP_SUCCESS,[]];
        $lottery = LotteryConfig::where('status',1)
            ->where('end_time','>',now())
            ->where('start_time','<',now())
            ->where('mall_id',$this->mid)
            ->where('style',$id)
            ->find();
        if (empty($lottery))
            throw new Exception('目前没有抽奖活动',HTTP_NOTACCEPT);
        $mid = $this->mid;
        $find = UserLottery::where('user_id',$this->user->id)
            ->where('lottery_config_id','=',function($sql) use ($id,$mid){
                $sql->name('lottery_config')
                    ->field('id')
                    ->where('mall_id',$mid)
                    ->where('status',1)
                    ->where('style',$id)
                    ->where('delete_time',null)
                    ->limit(0,1);
            })
            ->with('Config')
            ->append(['total_number'])
            ->find();
        if (!empty($find)){
            $data = ['end_time' => $find->Config->end_time];
            if (date('Y-m-d',strtotime($find['update_time'])) != date('Y-m-d') && $find->Config->type == 1) {
                $data['get_number'] = 0;
                $data['number'] = $find->Config->number;
            }
            $find->save($data);
        }else{
            $value = $lottery->toArray();
            $data = [
                'mall_id' => $this->mid,
                'user_id' => $this->user->id,
                'status' => 1,
                'lottery_config_id' => $value['id'],
                'number' => $value['number'],
                'end_time' => $value['end_time']
            ];
            UserLottery::create($data);
            $find = UserLottery::where('user_id',$this->user->id)
                ->where('lottery_config_id',$value['id'])
                ->with(['Config'])
                ->append(['total_number'])
                ->find();
        }

        $find = $find->toArray();
        return [HTTP_SUCCESS,$find];
    }

    public function lottery(int $style,string $update_time,int $type) : array{
        $lottery = Lottery::getUserLotteryFind((int)$this->user->id,$update_time,$style);
        switch ($type) {
            case 1://抽奖判断->积分扣除->扣除次数->随机选出奖品->记录数据
                $lottery->lotteryJudge()->lotteryIntegralDec()->minusNumber()->getLotteryReturn()->settlementLottery();
                break;
            case 2://随机选出商品
                $lottery->getLotteryReturn(true);
                break;
            case 3://抽奖判断->积分扣除->扣除次数->记录数据
                $lottery->setReturn()->lotteryJudge()->lotteryIntegralDec()->minusNumber()->settlementLottery();
                break;
        }
        return [HTTP_SUCCESS,$lottery->getReturn()];
    }


    public function lottery_commodity_receive(int $id, string $name, ?int $mobile, string $address,?int $type,?int $store_id){
        $logistics = LotteryLogistics::where('lottery_log_id',$id)->find();
        if (empty($logistics->id))
            throw new Exception('奖品领取错误',HTTP_NOTACCEPT);
        if (!empty($store_id) && $type == 2) {
            $store = Store::find($store_id);
            if (empty($store->id))
                throw new Exception('店铺不存在',HTTP_NOTACCEPT);
            $name = $store->name;
            $mobile = $store->mobile;
            $address = str_replace( ',','-',$store->district).$store->address;
        }
        $logistics->save([
            'store_id' => empty($store) ? 0 : $store->id,
            'name' => $name,
            'type' => $type,
            'mobile' => $mobile,
            'address' => $address,
            'update_time' => now()
        ]);
        LotteryLog::where('id',$id)->update(['update_time' => now(),'receive' => 1]);
        return [HTTP_SUCCESS,LotteryLogistics::where('lottery_log_id',$id)->find()];
    }


    public function lottery_log_list(int $page, int $size,array $data) : array{
        $where = [];
        if (!empty($data['type']))$where[] = ['type','=',$data['type']];
        if (!empty($data['receive']))$where[] = ['receive','=',$data['receive']];
        $list = LotteryLog::where('user_id',$this->user->id)
            ->where($where)
            ->where('type','>',1)
            ->with(['prize','logistics'])
            ->order('create_time DESC')
            ->paginate(['page' => $page,'list_rows' => $size])
            ->toArray();
        return [HTTP_SUCCESS,$list];
    }

    public function lottery_goods_receiving(int $id){
        LotteryLogistics::where('lottery_log_id',$id)->update([
            'update_time' => now(),
            'status' => 3
        ]);
        return [HTTP_SUCCESS,[]];
    }


    public function lottery_log_read(int $id) : array{
        $data = LotteryLog::where('id',$id)->with(['Logistics','prize'])->find()->toArray();
        return [HTTP_SUCCESS,$data];
    }

    public function lottery_goods_qrcode(int $id){
        global $mid;
        $qrcodeService = new QrcodeService();
        $store_id = LotteryLogistics::where('id',$id)->value('store_id');
        list($code, $qrcode) = $qrcodeService->verification(['ids' => [$id],'a' => 1,'store_id' => $store_id,'mall_id' => $mid]);
        if ($code !== HTTP_SUCCESS)
            throw new Exception('二维码生成失败', HTTP_NOTACCEPT);
        return [$code,$qrcode];
    }
}